package org.basis.advance.c1;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.FixedLengthFrameDecoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

/**
 * 定长消息解码器测试
 *
 * @author Mr_wenpan@163.com 2021/09/20 11:04
 */
@Slf4j
public class Server2 {

    public static void main(String[] args) throws InterruptedException {
        start();
    }

    static void start() throws InterruptedException {

        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(boss, worker);
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) throws Exception {
                    ChannelPipeline pipeline = ch.pipeline();
                    // 添加netty提供的定长消息解码器，定长消息长度为10。注意：这个handler必须在最前面，因为是这个handler将
                    // buffer 中的消息按照定长去读取，然后传递给下一个handler的。在这个handler前面的handler接收到的消息不是定长
                    // 为10的消息，有可能是多条消息，也有可能是半条消息
                    pipeline.addLast(new FixedLengthFrameDecoder(10));
                    pipeline.addLast(new LoggingHandler(LogLevel.INFO));
                }
            });

            // 同步绑定端口
            ChannelFuture channelFuture = serverBootstrap.bind(8080).sync();
            channelFuture.channel().closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }

    }
}
